<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>
    
    ES6 const变量声明及特性 - DSRBLOG
    
  </title>
  

  
  
  <link href="atom.xml" rel="alternate" title="DSRBLOG" type="application/atom+xml">
  <link rel="stylesheet" href="asset/css/style.min.css">
  <link rel="stylesheet" href="asset/css/doc.css">
  <script src="asset/app.js"></script>


</head>

<body> <section class="ct-body">
	<div class="container">
		<div class="columns is-variable bd-klmn-columns is-4 is-centered">
			<div class="column is-four-fifths">
				<div class="post-body single-content">
					
					<h1 class="title">
						ES6 const变量声明及特性
					</h1>


					<div class="media">
						
						
						<div class="media-content">
							<div class="content">
								<p>
									<span class="date">2022/07/03 22:43 下午</span>
									

									

									<br />
									<span class="tran-tags">Tags:</span>&nbsp;
									
									<a class="tag is-link is-light">#ES6新特性</a>
									

								</p>
							</div>
						</div>

					</div>
				</div>
				<article class="markdown-body single-content">
					<p><code>const</code>用于声明<strong>常量</strong>（值不能修改的量）</p>
<h2><a id="%E5%A3%B0%E6%98%8E%E6%A0%BC%E5%BC%8F" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>声明格式</h2>
<p>与<code>let</code>、<code>var</code>一致</p>
<pre class="line-numbers"><code class="language-js">const myID = 'DSR213';
</code></pre>
<h2><a id="%E7%89%B9%E6%80%A7" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>特性</h2>
<ol>
<li>一定要赋初始值</li>
</ol>
<pre class="line-numbers"><code class="language-js">const A; //报错，缺少初始化
</code></pre>
<ol start="2">
<li>一般常量使用大写（潜规则）</li>
<li>常量的值不能修改</li>
</ol>
<pre class="line-numbers"><code class="language-js">const myID = 'DSR213';
myID = 'DSRKafuu'; //报错
</code></pre>
<ol start="4">
<li>块级作用域</li>
</ol>
<pre class="line-numbers"><code class="language-js">{
    const myID = 'DSR213';
}
console.log(myID); //报错
</code></pre>
<ol start="5">
<li>对于数组和对象的元素修改，不算对常量的修改，不会报错</li>
</ol>
<pre class="line-numbers"><code class="language-js">const DSRTeam = ['DSRKafuu' , 'DSRLing' , 'DSR213'];
DSRTeam.push('jjmy8888'); 
//不报错，数组元素发生变化，但该常量指向的地址没有变化
</code></pre>

				</article>
				<div class="comments-wrap">
					<div class="share-comments">
						

						

						
					</div>
				</div><!-- end comments wrap -->
			</div>
		</div><!-- end columns -->
	</div><!-- end container -->
</section>  














<script src="asset/prism.js"></script>









</body>

</html>